package com.ltkj.baseplatform.service.impl;

import cn.hutool.core.util.IdcardUtil;
import com.ltkj.baseplatform.domain.SerGameData;
import com.ltkj.baseplatform.domain.SerGameMember;
import com.ltkj.baseplatform.domain.bo.SerGameMemberBo;
import com.ltkj.baseplatform.domain.bo.SerGameMemberQueryBo;
import com.ltkj.baseplatform.domain.vo.SerGameMemberVo;
import com.ltkj.baseplatform.mapper.SerGameDataMapper;
import com.ltkj.baseplatform.mapper.SerGameMemberBizMapper;
import com.ltkj.common.core.constant.CacheConstants;
import com.ltkj.baseplatform.mapper.SerGameMemberMapper;
import com.ltkj.baseplatform.service.ISerGameMemberService;
import com.ltkj.common.core.domain.R;
import com.ltkj.common.core.exception.ServiceException;
import com.ltkj.common.core.utils.DateUtils;
import com.ltkj.common.redis.service.RedisService;
import com.ltkj.common.security.utils.SecurityUtils;
import com.ltkj.system.api.RemoteOrderService;
import com.ltkj.system.api.domain.AppletOrderDetailVo;
import com.ltkj.system.api.domain.OrderDetailQueryDTO;
import com.ltkj.system.api.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 赛事成员Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-13
 */
@Service
public class SerGameMemberServiceImpl implements ISerGameMemberService 
{
    @Autowired
    private SerGameMemberMapper serGameMemberMapper;

    @Autowired
    private SerGameMemberBizMapper serGameMemberBizMapper;

    @Autowired
    private SerGameDataMapper serGameDataMapper;

    @Autowired
    private RemoteOrderService remoteOrderService;

    @Autowired
    private RedisService redisService;

    /**
     * 查询赛事成员
     * 
     * @param id 赛事成员主键
     * @return 赛事成员
     */
    @Override
    public SerGameMember selectSerGameMemberById(Long id)
    {
        return serGameMemberMapper.selectSerGameMemberById(id);
    }

    /**
     * 查询赛事成员列表
     * 
     * @param serGameMember 赛事成员
     * @return 赛事成员
     */
    @Override
    public List<SerGameMember> selectSerGameMemberList(SerGameMember serGameMember)
    {
        return serGameMemberMapper.selectSerGameMemberList(serGameMember);
    }

    /**
     * 新增赛事成员
     * 
     * @param serGameMember 赛事成员
     * @return 结果
     */
    @Override
    public int insertSerGameMember(SerGameMemberBo serGameMember)
    {
        SerGameData serGameData = serGameDataMapper.selectSerGameDataById(serGameMember.getGameId());
        //对成员的性别同赛事的限制一致
        /*if(serGameData.getSex()!=null && !serGameData.getSex().equals(serGameMember.getSex())){
            throw new ServiceException("成员的性别和赛事要求不一致！");
        }*/
        SerGameMember member = new SerGameMember();
        BeanUtils.copyProperties(serGameMember,member);
        member.setCreateTime(DateUtils.getNowDate());
        member.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        return serGameMemberMapper.insertSerGameMember(member);
    }

    /**
     * 批量新增赛事成员
     *
     * @param serGameMemberList 赛事成员列表
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSerGameMemberBacth(List<SerGameMemberBo> serGameMemberList,Long gameId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SerGameMember> members = new ArrayList<>();
        for (SerGameMemberBo serGameMemberBo : serGameMemberList) {
            SerGameMember member = new SerGameMember();
            BeanUtils.copyProperties(serGameMemberBo,member);
            member.setCreateTime(DateUtils.getNowDate());
            member.setCreateBy(loginUser.getUsername());
            member.setUserId(loginUser.getUserid());
            members.add(member);
        }
        int resultInt = 0;
        if(members.size() > 0){
            serGameMemberBizMapper.deleteGameMemberByUserIdAndGameId(loginUser.getUserid(),gameId);
            resultInt = serGameMemberBizMapper.insertSerGameMemberBatch(members);
        }
        return resultInt;
    }

    //批量新增前的校验
    @Override
    public Long validateGameMember(List<SerGameMemberBo> serGameMemberList) {
        if(serGameMemberList == null || serGameMemberList.size() == 0){
            throw new ServiceException("请输入需要添加的成员数据！");
        }
        Long gameId = serGameMemberList.get(0).getGameId();
        if(gameId == null){
            throw new ServiceException("请输入赛事数据！");
        }
        //依次校验每个字段  队名、赛事主键、成员名称、电话、身份证号
        int i = 0;
        int captainCount = 0;
        for (SerGameMemberBo serGameMemberBo : serGameMemberList) {
            i++;
            if(!StringUtils.hasText(serGameMemberBo.getTeamName())){
                throw new ServiceException("第"+ i +"个成员的队名为空！");
            }
            if(serGameMemberBo.getGameId() == null){
                throw new ServiceException("第"+ i +"个成员的赛事信息为空！");
            }
            if(!StringUtils.hasText(serGameMemberBo.getMemberName())){
                throw new ServiceException("第"+ i +"个成员的名称为空！");
            }
            if(!StringUtils.hasText(serGameMemberBo.getPhone())){
                throw new ServiceException("第"+ i +"个成员的手机号为空！");
            }
            if(!IdcardUtil.isValidCard(serGameMemberBo.getIdCard())){
                throw new ServiceException("第"+ i +"个成员的身份证号非法！");
            }
            if("1".equals(serGameMemberBo.getIsCaptain())){
                captainCount ++;
            }
        }
        if(captainCount != 1){
            throw new ServiceException("只能有一个队长！");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SerGameData serGameData = serGameDataMapper.selectSerGameDataById(gameId);
        if(serGameData == null){
            throw new ServiceException("赛事数据不存在！");
        }
        if(serGameData.getRealPersonNum().intValue() > serGameMemberList.size() || (serGameData.getRealPersonNum().intValue() + serGameData.getCandidateNum().intValue()) < serGameMemberList.size()){
            throw new ServiceException("参赛人数不符合赛事要求！");
        }
        //报名截止日期
        if(serGameData.getApplyEndTime() != null && serGameData.getApplyEndTime().compareTo(DateUtils.getNowDate()) == -1){
            throw new ServiceException("该赛事已过报名截止日期！");
        }
        //查询该赛事和正在下单的用户是否有未支付订单
        if (redisService.hasKey(CacheConstants.GAME_ORDER_NOT_PAY_KEY + serGameData.getId() + ":" + loginUser.getUserid())) {
            throw new ServiceException("您已经报名了该赛事，请支付相关订单！");
        }
        //查询订单详情获取状态和支付时间
        OrderDetailQueryDTO queryDTO = new OrderDetailQueryDTO();
        queryDTO.setTicketId(serGameData.getId());
        queryDTO.setTicketType("5");
        //2已支付
        queryDTO.setTicketStatus("2");
        R<List<AppletOrderDetailVo>> result = remoteOrderService.queryOrderDetail(queryDTO);
        if (com.ltkj.common.core.utils.StringUtils.isNull(result) || com.ltkj.common.core.utils.StringUtils.isNull(result.getData())){
            throw new ServiceException("查询报名状态失败！");
        }
        int applyNum = result.getData().size();//已报名人数
        boolean hasApplyFlag = false;//当前用户是否已报名该赛事
        for (AppletOrderDetailVo item : result.getData()) {
            //查询当前用户是否已报名该赛事
            if(loginUser.getUserid().equals(item.getUserId())){
                hasApplyFlag = true;
            }
        }
        //如果当前用户已报名该赛事，给出提示
        if(hasApplyFlag){
            throw new ServiceException("您已经报名了该赛事，请勿重复报名！");
        }
        //已报名的人数
        if(applyNum >= serGameData.getTotalSeat().intValue()){
            throw new ServiceException("报名席位已满！");
        }
        return gameId;
    }

    /**
     * 修改赛事成员
     * 
     * @param serGameMember 赛事成员
     * @return 结果
     */
    @Override
    public int updateSerGameMember(SerGameMemberBo serGameMember)
    {
        SerGameData serGameData = serGameDataMapper.selectSerGameDataById(serGameMember.getGameId());
        //对成员的性别同赛事的限制一致
        /*if(serGameData.getSex()!=null && !serGameData.getSex().equals(serGameMember.getSex())){
            throw new ServiceException("成员的性别和赛事要求不一致！");
        }*/
        SerGameMember member = new SerGameMember();
        BeanUtils.copyProperties(serGameMember,member);
        member.setUpdateTime(DateUtils.getNowDate());
        member.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        return serGameMemberMapper.updateSerGameMember(member);
    }

    /**
     * 批量删除赛事成员
     * 
     * @param ids 需要删除的赛事成员主键
     * @return 结果
     */
    @Override
    public int deleteSerGameMemberByIds(Long[] ids)
    {
        return serGameMemberMapper.deleteSerGameMemberByIds(ids);
    }

    /**
     * 删除赛事成员信息
     * 
     * @param id 赛事成员主键
     * @return 结果
     */
    @Override
    public int deleteSerGameMemberById(Long id)
    {
        return serGameMemberMapper.deleteSerGameMemberById(id);
    }

    @Override
    public SerGameMemberVo selectSerGameMemberVoById(Long id) {
        return serGameMemberBizMapper.selectSerGameMemberById(id);
    }

    @Override
    public List<SerGameMemberVo> selectSerGameMemberVoList(SerGameMemberQueryBo serGameMember) {
        return serGameMemberBizMapper.selectSerGameMemberList(serGameMember);
    }
}
